package service_blog_mirchen_com

import (
	"gen-go/BlogServices"
	"github.com/jinzhu/gorm"
)


//service结构
type MenuServiceHandler struct {
	orm *gorm.DB
}

//文章模型结构
type Menu struct {
	Id       int64  `gorm:"primary_key"`
	NavName  string
	ParentId int64
	Sort     int64
	Url      string
	Type     string
	CatId    int64
}

func NewMenuServiceHandler(getOrm *gorm.DB) *MenuServiceHandler {
	return &MenuServiceHandler{orm:getOrm}
}

func (msh *MenuServiceHandler) GetRelationCategoryByMenuId(menuid int64) (r *BlogServices.Category, err error) {
	return nil, err
}

func (msh *MenuServiceHandler) GetMenus() (r []*BlogServices.Menu, err error) {
	menus := &[]Menu{}
	err = msh.orm.Where("1=1").Find(menus).Error
	if err != nil {
		r = nil
	} else {
		r = []*BlogServices.Menu{}
		if len(*menus) > 0 {
			for _, menu := range *menus {
				r = append(r, &BlogServices.Menu{
					ID:menu.Id,
					CatId:menu.CatId,
					NavName:menu.NavName,
					Sort:menu.Sort,
					URL:menu.Url,
					Type:menu.Type,
					ParentId:menu.ParentId,
				})
			}
		}
	}
	return r, err
}

func (msh *MenuServiceHandler) GetNextMenus(parentId int64) (r []*BlogServices.Menu, err error) {
	menus := &[]Menu{}
	err = msh.orm.Where("parent_id=?", parentId).Find(menus).Error
	if err != nil {
		r = nil
	} else {
		r = []*BlogServices.Menu{}
		if len(*menus) > 0 {
			for _, menu := range *menus {
				r = append(r, &BlogServices.Menu{
					ID:menu.Id,
					CatId:menu.CatId,
					NavName:menu.NavName,
					Sort:menu.Sort,
					URL:menu.Url,
					Type:menu.Type,
					ParentId:menu.ParentId,
				})
			}
		}
	}
	return r, err
}

func (msh *MenuServiceHandler) GetMenuById(menuid int64) (r *BlogServices.Menu, err error) {
	menu := &Menu{}
	err = msh.orm.Where("id=?", menuid).First(menu).Error
	if err != nil {
		r = nil
	} else {
		r = &BlogServices.Menu{
			ID:menu.Id,
			CatId:menu.CatId,
			NavName:menu.NavName,
			Sort:menu.Sort,
			URL:menu.Url,
			Type:menu.Type,
			ParentId:menu.ParentId,
		}
	}
	return r, err
}
